package com.android.scanner.demo;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;



import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class Login extends Activity
{
	private EditText userId = null;
	private EditText passWord = null;
	private Button login = null;
	private Button cancel = null;
	
	private static String SERVLET_URL = "http://192.168.1.105:8080/ws/TestServlet";

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		//--------------------------------------------//
		
		/*String result = getResultFromServlet("Hello");
		System.out.println("**********" + result);
		
		String[] strArray = result.split("\\|\\|");
		String apkVersion = strArray[0].trim();
		String apkSize = strArray[1].trim();
		String apkPath = strArray[2].trim();
		
		int curVersion = getAPKVersion();
		int srvVersion = Integer.parseInt(apkVersion);
		if(curVersion != srvVersion)
		{
			Intent intent = new Intent();
			
			//intent.putExtra("apkVersion", apkVersion);
			//intent.putExtra("apkSize", apkSize);
			intent.putExtra("apkPath", apkPath);
			
			intent.setClass(Login.this, Update.class);
			Login.this.startActivity(intent);
		}
*/
		
		
		//--------------------------------------------//
		

		userId = (EditText) findViewById(R.id.et_userid);
		passWord = (EditText) findViewById(R.id.et_password);
		login = (Button) findViewById(R.id.btn_login);
		cancel = (Button) findViewById(R.id.btn_cancel);

		login.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				String userIdString = userId.getText().toString().trim();
				String passWordString = passWord.getText().toString().trim();
				Intent intent = new Intent();
			
				
				int flag = getLoginFlag(userIdString, passWordString);
				//int flag = 1;
				System.out.println("***********" + flag);
				if(flag!=1)
				{
					userId.setError("Plese type correct userId and passWord!");  
	                userId.requestFocus();  
	                return;
				}
				else 
				{
					intent.putExtra("userId", userIdString);
					intent.putExtra("passWord", passWordString);
					intent.setClass(Login.this, ScanDemo.class);
					Login.this.startActivity(intent);
				}
				
			}
		});
		
		cancel.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				Login.this.finish();
				
			}
		});
	}

	public int getLoginFlag(String v_userId, String v_passWord)
	{
		String nameSpace = "http://www.moleq.com/";
		String methodName = "Login";
		String endPoint = "http://moleq.com/iphonedemo/iphoneservice.asmx";
		String soapAction = "http://www.moleq.com/Login";

		SoapObject rpc = new SoapObject(nameSpace, methodName);
		rpc.addProperty("userID", v_userId);
		rpc.addProperty("pwd", v_passWord);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER10);

		envelope.bodyOut = rpc;
		envelope.dotNet = true;

		envelope.setOutputSoapObject(rpc);
		HttpTransportSE transport = new HttpTransportSE(endPoint);
		transport.debug = true;

		try
		{
			
			transport.call(soapAction, envelope);
			System.out.println("*****" + transport.requestDump);
			System.out.println("*******" + transport.responseDump);

		} catch (XmlPullParserException ex)
		{
			System.out.println("*****" + transport.requestDump);
			System.out.println("*******" + transport.responseDump);
			ex.printStackTrace();
		}

		catch (Exception e)
		{
			System.out.println("*****" + transport.requestDump);
			System.out.println("*******" + transport.responseDump);
			e.printStackTrace();

		}

		SoapObject object = (SoapObject) envelope.bodyIn;
		String result = object.getProperty(0).toString();
		System.out.println("%%%%%%%%%%%%%%%%%%" + result);
		return Integer.parseInt(result);
	}
	
	public String getResultFromServlet(String text)
	{
		String result = "";
		InputStream in = callService(text);
		if (in != null)
		{
			result = convertStreamToString(in);
		} else
		{
			result = "Error: Service not returning result";
		}
		return result;
	}

	private InputStream callService(String text)
	{
		InputStream in = null;

		try
		{
			URL url = new URL(SERVLET_URL);
			URLConnection conn = url.openConnection();

			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setRequestMethod("POST");
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.connect();

			DataOutputStream dataStream = new DataOutputStream(
					conn.getOutputStream());

			dataStream.writeBytes(text);
			dataStream.flush();
			dataStream.close();

			int responseCode = httpConn.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK)
			{
				in = httpConn.getInputStream();
			}else 
			{
				System.out.println("Response code is " + responseCode);
			}
		} catch (Exception ex)
		{

		}
		return in;
	}

	private static String convertStreamToString(InputStream is)
	{
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try
		{
			while ((line = reader.readLine()) != null)
			{
				sb.append(line + "\n");
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				is.close();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	private int getAPKVersion()
	{
		int sdcardVersion = 0;
		String apkFilePath = "sdcard/ScanDemo.apk";
		PackageManager pm = getPackageManager();
		PackageInfo info = pm.getPackageArchiveInfo(apkFilePath,PackageManager.GET_ACTIVITIES);
		if(info !=null)
		{
			sdcardVersion = info.versionCode;
			System.out.println("***********" + sdcardVersion);
		}
		
		return sdcardVersion;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if ((event.getAction() == KeyEvent.ACTION_DOWN)
				&& (keyCode == KeyEvent.KEYCODE_BACK))
		{
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onAttachedToWindow()
	{
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
		super.onAttachedToWindow();
	}
}